from flask import Blueprint, jsonify, request
from data.db.db_manager import DBManager
from web.services.market_data_service import MarketDataService

favorite_bp = Blueprint('favorite', __name__, url_prefix='/api/favorite')
db_manager = DBManager()
market_service = MarketDataService()

@favorite_bp.route('/stocks', methods=['GET'])
def get_favorite_stocks():
    """获取自选股票列表"""
    try:
        user_id = request.args.get('user_id')
        if not user_id:
            return jsonify({
                "status": "error",
                "message": "user_id is required"
            }), 400
            
        stocks = db_manager.get_favorite_stocks(user_id)
        return jsonify({
            "status": "ok",
            "data": [{
                "symbol": stock['stock_code'],
                "name": stock['stock_name'],
                "created_at": stock['created_at'],
                "updated_at": stock['updated_at']
            } for stock in stocks]
        })
        
    except Exception as e:
        print(f"Get favorite stocks error: {str(e)}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@favorite_bp.route('/stocks', methods=['POST'])
def add_favorite_stock():
    """添加自选股票"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        code = data.get('code')
    
        
        if not all([user_id, code]):
            return jsonify({
                "status": "error",
                "message": "user_id and stock code are required"
            }), 400
            
        # 通过市场数据服务查找完整的股票信息
        stock_info = market_service.get_symbol_info(code)
        if not stock_info:
            return jsonify({
                "status": "error",
                "message": f"Stock not found with code: {code}"
            }), 404
            
        # 保存到数据库
        db_manager.add_favorite_stock(
            user_id=user_id,
            stock_code=stock_info['ticker'],
            stock_name=stock_info['name']
        )
        
        return jsonify({
            "status": "ok",
            "data": stock_info
        })
        
    except Exception as e:
        print(f"Add favorite stock error: {str(e)}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@favorite_bp.route('/stocks/<stock_code>', methods=['DELETE'])
def remove_favorite_stock(stock_code):
    """删除自选股票"""
    try:
        user_id = request.args.get('user_id')
        if not user_id:
            return jsonify({
                "status": "error",
                "message": "user_id is required"
            }), 400
            
        db_manager.remove_favorite_stock(user_id, stock_code)
        return jsonify({"status": "ok"})
        
    except Exception as e:
        print(f"Remove favorite stock error: {str(e)}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500 